﻿namespace Gamelight.Graphics
{
	internal class EllipseDrawer
	{
		public void DrawEllipse(
			int[,] pixels,
			double[,] antialiasPixels,
			int[] column_affected,
			int[] min_y_affected,
			int[] max_y_affected,
			int counter,
			int antialiasCounter,
			double centerX, double centerY, double radiusX, double radiusY, bool allowAntialias)
		{
			// hrmph
			centerX -= .5;
			centerY -= 1;

			int minX = (int)(centerX - radiusX - 2);
			int minY = (int)(centerY - radiusY - 2);
			int maxX = (int)(centerX + radiusX + 2);
			int maxY = (int)(centerY + radiusY + 2);
			minX = minX < 0 ? 0 : minX;
			minY = minY < 0 ? 0 : minY;

			radiusX *= 2;
			radiusY *= 2;

			double largerRadius = radiusX > radiusY ? radiusX : radiusY;
			double radiusXratio = largerRadius / radiusX;
			double radiusYratio = largerRadius / radiusY;

			int x, y;
			for (x = minX; x < maxX; ++x)
			{
				column_affected[x] = counter;
				max_y_affected[x] = maxY;
				min_y_affected[x] = minY;
				for (y = minY; y < maxY; ++y)
				{
					double dy = 2 * (centerY - y) * radiusYratio;
					double dx = 2 * (centerX - x) * radiusXratio;
					double d = System.Math.Sqrt(dx * dx + dy * dy);
					if ((allowAntialias && largerRadius - 1 > d) || (!allowAntialias && largerRadius > d))
					{
						pixels[x, y] = counter;
						// totally in
					}
					else if (largerRadius + 1 < d)
					{
						// totally out
					}
					else if (allowAntialias)
					{
						double solidness = (largerRadius + 1 - d) / 2.0;
						pixels[x, y] = antialiasCounter;
						antialiasPixels[x, y] = solidness;
					}
				}
			}
		}
	}
}
